package com.moss.cloud.base.biz.listener;

import com.moss.cloud.base.biz.event.*;
import com.moss.cloud.common.core.constant.MsgTopic;
import com.moss.cloud.common.core.enums.MsgActionEnum;
import com.moss.cloud.common.core.enums.MsgTypeEnum;
import com.moss.cloud.common.core.model.dto.MessageDTO;
import com.moss.cloud.common.core.model.dto.TenantInfoDTO;
import com.moss.cloud.common.security.component.MessageEventSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 租户事件处理中心--此类消息必须是事务处理完成之后再调用
 *
 * @author 瑾年
 * @date 2024年1月22日
 */
@Slf4j
@Component
public class TenantListener {

    private final MessageEventSender messageEventSender;

    public TenantListener(MessageEventSender messageEventSender) {
        this.messageEventSender = messageEventSender;
    }

    /**
     * 监听租户信息更新事件
     *
     * @param event
     */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handleTenantInfoEvent(TenantInfoEvent event) {
        log.info("监听租户信息更新事件->租户:{}", event.getTenantFrom().getTenant().getTenantName());
        TenantInfoDTO tenantInfoDTO = new TenantInfoDTO();
        TenantInfoDTO.Tenant tenant = new TenantInfoDTO.Tenant();
        TenantInfoDTO.TenantLegal tenantLegal = new TenantInfoDTO.TenantLegal();
        BeanUtils.copyProperties(event.getTenantFrom().getTenant(), tenant);
        BeanUtils.copyProperties(event.getTenantFrom().getTenantLegal(), tenantLegal);
        tenantInfoDTO.setTenant(tenant);
        tenantInfoDTO.setTenantLegal(tenantLegal);
        messageEventSender.sendMessage(MsgTopic.TENANT_INFO_UPD_MESSAGE, new MessageDTO(MsgTypeEnum.ONE.name(), MsgActionEnum.UPDATE.name(), event.getTenantFrom()));
    }

    /**
     * 监听租户状态改变事件
     *
     * @param event
     */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handleTenantStatusEvent(TenantStatusEvent event) {
        log.info("监听租户状态改变事件->租户ID:{}", event.getTenantStatusDTO().getTenantId());
        messageEventSender.sendMessage(MsgTopic.TENANT_STATUS_CHANGE_MESSAGE, new MessageDTO(MsgTypeEnum.ONE.name(), MsgActionEnum.UPDATE.name(), event.getTenantStatusDTO()));
    }


}
